<?php

namespace app\api\controller;
use app\admin\model\CouponRecord;
use app\api\service\OrderService;
use app\api\service\RoomService;
use app\common\controller\Api;
use app\common\model\Advance;
use app\common\model\Area;
use app\common\model\Goodorder;
use app\common\model\Lights;
use app\common\model\Occupants;
use app\common\model\Pauserecords;
use app\common\model\Payment;
use app\common\model\Rooms;
use app\common\model\Upgraderules;
use app\manystore\model\ManystoreShop;
use think\Cache;
use think\Db;
error_reporting(E_ERROR);
/**
 * 门店
 */
class Order extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();

    }


    public function order_exists(){
        $Occupants=Occupants::where('user_id','=',$this->auth->id)->where('shop_id','=',input('shop_id'))->where('status','=',0)->find();
        if($Occupants){
            $this->success('有正在参与的订单',['id'=>$Occupants['id']]);
        }else{
            $this->error('无正在参与的订单');
        }
    }

    /*
     * 订单详情
     */
    public function order_detail(){
        if (!$id= input('id')) {
            $this->error(__('请选择订单'));
        }
        if (!$type= input('type')) {
            $this->error(__('请选择订单'));
        }
        //1是预约 2是订单
        if($type==1){
            $info=\app\common\model\Reservations::field('id,shop_id,room_id,order_no,deposit,balance_deduction,final_amount,pay_time,cancel_time,penalty_fee,deposit_status,expire_pay_time')->where('id',$id)->find();
        }else{
            $info=Occupants::field('id,join_time,shop_id,room_id,reservations_id,join_method,leave_time,status,user_id,unit_price,lights_id,pause_status,gift_time')->where('id',$id)->find();
        }

        $shop=ManystoreShop::where('id',$info['shop_id'])->find();
        $room=Rooms::where('id',$info['room_id'])->find();
        if($info){
            $info['shared_table'] = $room['shared_table'];
            //如果是订单的详情
            //预约信息
            $info['goodinfo']=[];
            if($type==1){
                $info['reservations_id']=$id;
            }
            if($info['reservations_id']!=null){
                $Reservations= \app\common\model\Reservations::where('id',$info['reservations_id'])->find();
                $info['reservations_count']=$Reservations['number_of_people'];
                $info['reservations_time']=timesf($Reservations['start_time'],$Reservations['end_time']);
                $info['reservations_phone']=$Reservations['phone'];
                $info['deposit']=$Reservations['deposit'];
            }else{
                $info['deposit']=0;
            }


            if($type==2){
                //查询一共暂停了多久

                $now_time=time();
                $order_server=new OrderService();
                $totalPauseDuration= $order_server->totalPauseDuration($id,$now_time);

                if($info['gift_time']>0){
                    $info['gift_time']=$info['gift_time']/60;
                }

                $info['join_time_second']=$now_time-$info['join_time']-$totalPauseDuration;
                //获取灯码
                $info->code = Lights::where('id', $info['lights_id'])->value('code');
                $order_stutus=$info['status'];
                $info['order_status']=$info['status'];
                if($info['status']==2){
                    $info['status']=3;
                }
                if($info['status']==0){
                    $info['status']=1;
                }
                $info['join_method']=$info['join_method']==0?'现场扫码':'线上';

                if($order_stutus==0||$order_stutus==1){
                    $occupants=Occupants::where('occupants.shop_id',$info['shop_id'])->with(['light'])->where('room_id',$info['room_id'])->where('occupants.status','<>',2)
                        ->select();

                    $occupant_info = [];
                    //正在玩的
                    foreach ($occupants as $item) {
                        $user=\app\admin\model\User::where('id',$item['user_id'])->find();
                        $occupant_info[] = [
                            'user_info' => [
                                'id' => $user->id,
                                'name' => $user->username,
                                'avatar' => $user->avatar,
                                'link_img' => $user->link_img,
                                'light_code'=>$item->light['code'],
                                'gender'=>$user->gender,
                            ], // 用户信息
                            'status' => '正在使用' // 状态
                        ];
                    }
                    //以预约的
                    $reservations = Db::table('fa_reservations')
                        ->where('start_time', '<',  date('Y-m-d H:i:s'))
                        ->where('end_time', '>',  date('Y-m-d H:i:s'))
                        ->where('room_id', '=', $info['room_id'])
                        ->value('(number_of_people-number_used)')?? 0; // 获取正在进行的预约
                    for ($i = 0; $i<$reservations; $i++) {
                        $occupant_info[] = [
                            'status' => '已预约' // 状态
                        ];
                    }
                    $occupied_count = count($occupants);
                    $reserved_count =$reservations; // 预约人数

                    // 获取空闲位置数量
                    $total_positions = $room['capacity']; // 包间总位置

                    $free_count = $total_positions - ($occupied_count + $reserved_count); // 计算空闲位置数
                    //人员信息
                    // 添加空闲位置信息
                    for ($i = 0; $i < $free_count; $i++) {
                        $occupant_info[] = [
                            'status' => '空闲' // 状态
                        ];
                    }
                    $info['userinfo']=$occupant_info;
                }
                if($order_stutus==1||$order_stutus==2){
                    //商品信息
                    $service = new OrderService();
                    $money_info=$service->order_money($id);

                    $goodinfo=Goodorder::where('occupants_id',$id)->field('id,goodimage,goodname,spec,num,price,total')->select();

                    $info['goodinfo']=$goodinfo;
                    //商品总额
                    $info['goodmoeny']=$money_info['good_tatal'];
                    //游玩金额
                    $info['ywmoney']=$money_info['yw_money'];


                    //小计
                    $info['total']=$info['goodmoeny']+ $info['ywmoney'];



                    ///用户金额信息
                    $user=\app\admin\model\User::where('id',$this->auth->id)->find();
                    $info['user_balance']=$user['money'];
                    $info['month_card']=$user['month_card'];
                    //还需要支付
                    $info['left_money']=round( max(0, $info['total'] - $user['money'] - $info['deposit']),2);


                    //已完成查询付款信息
                    if($order_stutus==2){

                      $payment_id=  Advance::where('order_id','=',$id)->value('payment_id');
                       $Advance= Advance::where('payment_id','=',$payment_id)->field('*')->where('pay_userid',$info['user_id'])->where('pay_status',1)->select();
                        $usermoney=0;
                        foreach ($Advance as $item) {
                            $occupants = Occupants::where('id', $item['order_id'])->find();
                            //灯码
                            $item->code = Lights::where('id', $occupants['lights_id'])->value('code');
                            //用户信息
                           $userinfo= \app\common\model\User::where('id', $item['user_id'])->field('nickname,avatar')->find();
                            //游戏时长
                            $item->nickname=$userinfo['nickname'];
                            $item->avatar=$userinfo['avatar'];
                            $item->time_long = gmdate("H:i:s", $occupants['leave_time'] - $occupants['join_time']);
                            $item->is_my=$occupants['user_id']==$this->auth->id?1:0;
                            $item->reservations_time=timesf(date("Y-m-d H:i:s", $occupants['join_time'] ),  date("Y-m-d H:i:s",$occupants['leave_time'] ) );

                            //游玩金额
                            $item->ywmoney=$item->play;
                            $usermoney+=$item->total;
                        }
                       $Advance_info= Advance::where('order_id',$id)->find();

                        $payment_info = Payment::where('id', $Advance_info['payment_id'])->find();
                        //订单号
                        $info->order_no = $payment_info['order_no'];
                        if ($payment_info['method'] == '微信') {
                            $info->pay_type = generatePayType($payment_info['balance'], $payment_info['paid'], $payment_info['deposit']);
                        } else {
                            $info->pay_type = '月卡';
                        }
                        //支付时间
                        $info['pay_time'] = date("Y-m-d H:i:s", $payment_info['pay_time']);
                        if($payment_info['coupon_record_id']!=null){
                            $record=CouponRecord::where('id','=',$payment_info['coupon_record_id'])->find();
                            $info->record_money='￥'.$record['money'].'(满'.$record['min_money'].'减)'.$record['money'];
                        }else{
                            $info->record_money='无';
                        }

                        $info['usermoney']=$usermoney;
                        $info->userinfos=$Advance;
                    }
                }
                if(input('daifu')==1){


                    $occupants = Occupants::where('id', $id)->find();
                    //灯码
                    $info->code = Lights::where('id', $occupants['lights_id'])->value('code');
                    //用户信息
                    $userinfo=\app\common\model\User::where('id', $occupants['user_id'])->field('nickname,avatar')->find();
                    $info->nickname=$userinfo['nickname'];
                    $info->avatar=$userinfo['avatar'];
                    $info->is_my=$occupants['user_id']==$this->auth->id?1:0;
                    //游戏时长
                    $info->time_long = gmdate("H:i:s", $occupants['leave_time'] - $occupants['join_time']);


                    $service = new OrderService();
                    $df_money_info=$service->order_money($id);

                    //$hour=ceil((time()-$info['join_time'])/60);
                    //游玩金额
                    $info->ywmoney=$df_money_info['yw_money'];

                }

            }else{
                if($info['deposit_status']==1){
                    $info['status']=0;
                }
                if($info['deposit_status']==0){
                    $info['status']=2;
                    $info['pay_second']=$info['expire_pay_time']-time()<0?0:$info['expire_pay_time']-time();
                }
                if($info['deposit_status']==2){
                    $info['status']=4;
                }

                $info['join_method']='预约';
                //如果是预约的详情
                $info['reservations_id']=$info['id'];
                //灯码
                $info['lightcode']='无';
                //开始时间
                $info['join_time_text']='无';
                //结束时间
                $info['leave_time_text']='无';

                //支付方式
                $info['pay_type']= generatePayType($info['balance_deduction'],$info['final_amount'] ,0);

                //支付时间
                $info['pay_time']=$info['pay_time']==null?'无':date("Y-m-d H:i:s", $info['pay_time']);

                //取消状态显示取消时间
                if($info['deposit_status']==2){
                    $info['cancel_time']=date("Y-m-d H:i:s", $info['cancel_time']);
                    //退回金额
                    $info['back_mobey']=$info['deposit']-$info['penalty_fee'];
                }
            }


            $info['theme']=$room['theme'];
            $info['shop_name']=$shop['name'];
            $info['room_name']=$room['title'];
            $info['is_put']=$room['shared_table'];
            $info['play_money']=$room['deposit'];
            $this->success('请求成功',$info);
        }else{
            $this->error('无订单');
        }
    }
    //加入
    public function join_room(){


        $data = input('post.');
        $cacheKey = 'submit_' . md5(serialize($data));
        // 检查缓存中是否存在该键名
        if (Cache::has($cacheKey)) {
            $this->error(__('您点的太快了'));
        }
        Cache::set($cacheKey, true, 3);

        //预约
        db::startTrans();
        if ($reservations_id = input('reservations_id')) {
            $Reservations = \app\common\model\Reservations::where('id', $reservations_id)->where('deposit_status', 1)->find();
            if ($Reservations['reservation_status'] == 2) {
                $this->error(__('此预约已结束'));
            }
            $room_id = $Reservations['room_id'];
            $shop_id = $Reservations['shop_id'];
            if (!$lights_id = input('lights_id')) {
                $this->error(__('请先扫灯码'));
            }

            //判断预约加入人数够不够
            $yy_count=Occupants::where('reservations_id',$reservations_id)->count();
            if($Reservations['number_of_people']<=$yy_count){
                $this->error(__('已超过预约人数'));
            }
            //修改预约的状态 变成已加入
            \app\common\model\Reservations::where('id',$reservations_id)->update(['reservation_status'=>1,'number_used'=>$Reservations['number_used']+1]);

        } else {
            if (!$room_id = input('room_id')) {
                $this->error(__('请选择包间或者大厅'));
            }
//            if (!$shop_id = input('shop_id')) {
//                $this->error(__('请选择门店'));
//            }
            if (!$lights_id = input('lights_id')) {
                $this->error(__('请输入灯码'));
            }
        }
        $room=Rooms::where('id',$room_id)->find();
        $shop_id=$room['shop_id'];
        $service=new RoomService();
        $incount=$service->order_in($room_id,$shop_id);
        if($room['capacity']<=$incount){
            $this->error(__('此房间已满'));
        }
        //判断灯码使用情况
        $light=Occupants::where('lights_id',$lights_id)->where('status','<>',2)->where('shop_id',$shop_id)->find();
        if($light){
            $this->error(__('当前灯号已占用'));
        }
        //是否有进行中
        $is_in=Occupants::where('user_id',$this->auth->id)->where('status','<>',2)->where('shop_id',$shop_id)->find();
        if($is_in){
            $this->error(__('您有订单正在进行中'));
        }



       $result= Occupants::create([
            'user_id'=>$this->auth->id,
            'room_id'=>$room_id,
            'shop_id'=>$shop_id,
            'join_time'=>time(),
            'status'=>0,
            'lights_id'=>$lights_id,
            'reservations_id'=>$reservations_id,
            'unit_price'=>$room['deposit']
        ]);
        db::commit();
        $this->success('请求成功',['id'=>$result->id]);
    }

    /*
     * 输入灯码绑定
     */
    public function light(){
        if (!$shop_id= input('shop_id')) {
            $this->error(__('请选择门店'));
        }
        if (!$code= input('code')) {
            $this->error(__('请输入灯码'));
        }
       $light= Lights::field('id,code')->where('code',$code)->where('shop_id',$shop_id)->find();
        if(!$light){
            $this->error(__('该灯码不存在'));
        }

        $occ=Occupants::where('lights_id',$light['id'])->where('status','<>',2)->find();
        if($occ){
            $this->error(__('当前灯号已占用'));
        }


        if($light){
            $this->success('请求成功',$light);
        }else{
            $this->error(__('该灯码不存在'));
        }
    }

    /*
     * 帮朋友代付列表
     */
    public function payment_user_list()
    {
        if (!$id = input('id')) {
            $this->error(__('请选择订单'));
        }
        $Occupants = Occupants::where('id', $id)->find();
        $list = Occupants::field('id,leave_time,join_time,unit_price,user_id,status')->with(['user','light'])->where('room_id', $Occupants['room_id'])->where('occupants.status', 'in', [0, 1])->select();
        $service=new OrderService();
        foreach ($list as $item) {
            $item->getRelation('light')->visible(['code']);
            $item->getRelation('user')->visible(['username','avatar']);
            //计算价格
            if($item->user_id==$this->auth->id){
                $item->is_my=1;
            }else{
                $item->is_my=0;
            }

            $money_info=$service->order_money($item->id);
            $item->total=$money_info['yw_money']+$money_info['good_tatal'];

            if($item->status==0){
                $differenceInSeconds =time()-$item['join_time'];
            }else{
                $differenceInSeconds = $item['leave_time']-$item['join_time'];
            }


            $timeDifference = sprintf("%02d:%02d:%02d", ($differenceInSeconds / 3600), ($differenceInSeconds % 3600) / 60, $differenceInSeconds % 60);
            $item->duration=$timeDifference;
        }
        $this->success('请求成功', $list);
    }


    //创建支付订单
    public function add_order()
    {
        $method = input('method');

        $user = \app\common\model\User::where('id', '=', $this->auth->id)->find();

        $occupants = occupants::where('id', 'in', input('ids'))->where('status', '<>', 2)->select();
        $service = new OrderService();
        $advance = [];
        $sumtotal = 0;
        $sum_yfmoney=0;
        $deposit_left=0;
        db::startTrans();
        foreach ($occupants as $item) {
            $money_info = $service->order_money($item->id);
            $yw_moeny = $money_info['yw_money'];
            $good_tatal = $money_info['good_tatal'];
            $total = $yw_moeny + $good_tatal;
            $advance[] = [
                'play' => $yw_moeny,
                'goods' => $good_tatal,
                'total' => $total,
                'order_id' => $item['id'],
                'user_id' => $item['user_id'],
                'pay_userid' => $this->auth->id
            ];
            $sumtotal += $total;
            $sum_yfmoney+=$yw_moeny;
        }
        $user_occ = occupants::where('id', 'in', input('ids'))->where('status', '<>', 2)->where('user_id', $this->auth->id)->find();

        if ($method == '月卡') {
            if (count($occupants) > 1 || $occupants[0]['user_id'] != $this->auth->id) {
                $this->error('月卡不可代付');
            }
            if($user['month_card']<=0){
                $this->error('月卡数量不足');
            }
            $sumtotal=$sumtotal-$yw_moeny;

//            $deposit_used = 0;
//            $balance_used = 0;
//            $remaining_amount = 0;
//            $coupon_amount = 0;

        }


            //有优惠券
            if (input('coupon_record_id') != null && input('coupon_record_id') != "") {
                $coupon_info = $service->loadCoupon(['coupon_record_id' => input('coupon_record_id'), 'amount' => $sumtotal, 'user_id' => $this->auth->id]);
                $coupon_amount = $coupon_info['coupon_discount'];
            } else {
                $coupon_amount = 0;
            }

            //先查询押金
          //  $user_occ = occupants::where('id', 'in', input('ids'))->where('status', '<>', 2)->where('user_id', $this->auth->id)->find();
            $deposit = 0;
            if ($user_occ['reservations_id'] != null) {
                $deposit = \app\common\model\Reservations::where('id', $user_occ['reservations_id'])->where('deposit_status', 1)->value('deposit');
            }

            $user_money = $user['money'];

            // 计算抵扣

            $leftmoeny = $sumtotal - $coupon_amount;//扣掉优惠券金额
            $deposit_used = min($deposit, $leftmoeny); // 使用可用的押金

            //押金剩余多少
            $deposit_left=$deposit-$deposit_used;


            $remaining_amount = $leftmoeny - $deposit_used; // 剩余需要支付的金额
            $balance_used = min($user_money, $remaining_amount); // 使用余额抵扣剩余金额
            $remaining_amount -= $balance_used; // 更新最后的剩余金额



        $payment = Payment::create([
            'user_id' => $this->auth->id,
            'method' => $method,
            'total' => $sumtotal,
            'deposit' => $deposit_used,
            'balance' => $balance_used,
            'paid' => $remaining_amount,
            'order_no' => order_no(),
            'coupon_amount' => $coupon_amount,
            'coupon_record_id' => input('coupon_record_id'),
            'left_money'=>$deposit_left,
            'reservations_id'=>$user_occ['reservations_id']
            ,'order_id'=>$user_occ['id'],

        ]);
        foreach ($advance as $item) {
            $item['payment_id'] = $payment->id;
            Advance::create($item);
        }
        db::commit();
        //判断够不够支付
        if ( $remaining_amount == 0) {
            $service->order_success($payment->id);
            $this->success('请求成功', [
                'is_pay' => 0
            ]);
        } else {
            $this->success('请求成功', [
                'is_pay' => 1,
                'id' => $payment->id,
                'order_no' => $payment->order_no,
            ]);
        }


    }

    //订单支付
    public function Order_payment()
    {
        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $order_no = order_no();
        $result=\app\common\model\Payment::where('id','=',$id)->where('pay_status','=',0)->update(['order_no'=>$order_no]);
        if($result===0){
            $this->error('当前订单已支付');
        }
        $payment = OrderService::order_payment($id, $this->auth->id,'结算');
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }

    //订单列表
    public function order_list() {
        // 获取请求类型
        $type = input('type');

        // 初始化结果数组
        $list = [];
        $Reservations=[];
        // 查询预约
        if ($type == 0 || $type == 2 || $type == 4||$type==null) {
            $Reservations = \app\common\model\Reservations::where('user_id', $this->auth->id)
                ->where('reservation_status', 0)
                ->field('id,deposit,number_of_people,start_time,end_time,deposit_status')
                ->with(['rooms', 'shop']);

            // 根据$type添加条件
            if ($type == 0&&$type!='') { // 待开始
                $Reservations->where('deposit_status', 1);
            } elseif ($type == 2) { // 待支付
                $Reservations->where('deposit_status', 0);
            } elseif ($type == 4) { // 已取消
                $Reservations->where('deposit_status', 2);
            }

            $Reservations = $Reservations->select();

            foreach ($Reservations as $item) {
                $item->getRelation('rooms')->visible(['id', 'title', 'capacity', 'image_url','theme','capacity']);
                $item->getRelation('shop')->visible(['name', 'id']);
                $item->timerange = date('H:i', strtotime($item['start_time'])) . '-' . date('H:i', strtotime($item['end_time']));
                $item->unit_price = $item['deposit'] / $item['number_of_people'];
                if($item->deposit_status==1){
                    $item->status=0;
                }
                if($item->deposit_status==0){
                    $item->status=2;
                }
                if($item->deposit_status==2){
                    $item->status=4;
                }
            }

            // 将结果设置为$Reservations
            $result = $Reservations;
        }

        if ($type == 1 ||$type==2|| $type == 3||$type==null) {
            // 查询入住信息
            $list = Occupants::where('user_id', $this->auth->id)
                ->field('id,unit_price,status,join_time,leave_time')
                ->with(['rooms', 'shop'])
                ->order('id desc');

            // 根据$type添加条件
            if ($type == 1) { // 进行中
                $list->where('occupants.status', 0);
            }
            if ($type == 2) { // 进行中
                $list->where('occupants.status', 1);
            }
            elseif ($type == 3) { // 已结束
                $list->where('occupants.status', 2);
            }

            $list = $list->select();

            foreach ($list as $item) {
                $item->order_status=$item->status;
                $item->getRelation('rooms')->visible(['id', 'title', 'capacity', 'image_url','theme','capacity']);
                $item->getRelation('shop')->visible(['name', 'id']);
                if ($item->status == 0) {
                    // 进行中计算游玩时间
                    $now_time=time();
                    $order_server=new OrderService();
                    $totalPauseDuration= $order_server->totalPauseDuration($item->id,$now_time);

                    $item->yw_time = gmdate("H:i:s", time() - $item->join_time-$totalPauseDuration);
                }
                if ($item->status == 2) {
                    $item->timerange = date('H:i', $item['join_time']) . '-' . date('H:i', $item['leave_time']);
                }
                if ($item->status==2){
                    $item->status=3;
                }
                if ($item->status==0){
                    $item->status=1;
                }



            }

            // 将结果设置为$list
            $result = $list;
        }

        // 返回成功结果
        $this->success('请求成功', array_merge($list,$Reservations));
    }


    public function Notice(){
        $occupants=  occupants::where('id','=',input('occupants_id'))->find();
        $room=Rooms::where('id',$occupants['room_id'])->find();

        $notice=new Notice();
        $notice->Notice($occupants['room_id'],$occupants['shop_id'],$occupants['id'],$room['room_number']. "房间呼叫",$occupants['shop_id']);
        $this->success('呼叫成功', []);
    }




    /*
     * 结束订单
     */
    public function end_order(){
        if (!$id = input('id/d')) {
            $this->error('订单ID不能为空');
        }
        $occupants=Occupants::where('id',$id)->find();
        if($occupants['status']!=0){
            $this->error('当前订单已结束');
        }
        //如果有暂停 结束
        $Pause = Pauserecords::where('occupant_id', $id)->where('status', 1)->find();
        if ($Pause) {
            $time = time();
            Pauserecords::where('id', $Pause['id'])->update(['status' => 2, 'resume_time' => $time]);
            Occupants::where('id', $id)->update(['pause_status' => 1, 'pause_time' =>$occupants['pause_time']+ $time - $Pause['pause_time']]);
        }
        Occupants::where('id',$id)->update(['status'=>1,'leave_time'=>time()]);
        $this->success('请求成功', []);
    }



    //查询进行中的订单
    public function order_in_id(){
        $Lights= Lights::where('id',input('lights'))->find();
        if(!$Lights){
            $this->error('灯码不存在');
        }

        $Occupants=Occupants::where('user_id',$this->auth->id)->where('shop_id','=',$Lights['shop_id'])->where('status','<>',2)->order('id desc')->find();
        if($Occupants){
            $this->success('请求成功', ['in'=>1,'id'=>$Occupants['id'],'status'=>$Occupants['status']]);
        }else{
            $this->success('请求成功', ['in'=>0]);
        }

    }





}
